package org.sanguine.study.hometasks.second;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Task6 {
	public static class Polynomial {
		private Map<Integer, Double> coefficients;
		
		/**
		 * Create new Polynomial with presented coefficients by order from highest to lowest
		 * @param coefficients
		 * @throws IllegalArgumentException if coefficients aren't present
		 */
		
		public Polynomial(Double ... coeffs) {
			if (coeffs != null && coeffs.length > 0) {
				coefficients = new HashMap<>(coeffs.length);
				Integer rang = coeffs.length - 1;
				for (Double c : coeffs) coefficients.put(rang--, c);
			} else throw new IllegalArgumentException("Coefficients must be set");
		}
		
		/**
		 * Return degree of polynomial
		 * @return degree of polynomial from zero
		 */
		
		public int getDegree() {
			return Collections.max(coefficients.keySet());
		}
		
		public Double getCoefficient(int rank) {
			return coefficients.get(rank);
		}
		
		public Polynomial add(Polynomial another) {
			if (another == null) return this;
			
			Double[] newCoeffs;
			int degree = coefficients.size() - 1;
			int anotherDegree = another.coefficients.size() - 1;
			
			if (degree >= anotherDegree) {
				newCoeffs = new Double[degree + 1];
				int i = degree;
				while (i > anotherDegree) {
					newCoeffs[degree - i] = coefficients.get(i);
					i--;
				}
				while (i >= 0) {
					newCoeffs[degree - i] = coefficients.get(i) + another.coefficients.get(i);
					i--;
				}
			} else {
				newCoeffs = new Double[anotherDegree + 1];
				int i = anotherDegree;
				while (i > degree) {
					newCoeffs[anotherDegree - i] = another.coefficients.get(i);
					i--;
				}
				while (i >= 0) {
					newCoeffs[anotherDegree - i] = coefficients.get(i) + another.coefficients.get(i);
					i--;
				}
			}
			
			return new Polynomial(newCoeffs);
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result
					+ ((coefficients == null) ? 0 : coefficients.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (!(obj instanceof Polynomial))
				return false;
			Polynomial other = (Polynomial) obj;
			if (coefficients == null) {
				if (other.coefficients != null)
					return false;
			} else if (!coefficients.equals(other.coefficients))
				return false;
			return true;
		}
		
		
	}

}
